package com.gzy.studentsociety.web;

import com.gzy.studentsociety.dao.*;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Student;
import com.gzy.studentsociety.entity.Member;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import java.rmi.ServerException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "student",urlPatterns = "/student/*")
public class StudentServlet extends RouteServlet{
    //    在servlet里面添加studentDao属性
    private StudentDao studentDao = new StudentDaoImpl();
    private MemberDao memberDao = new MemberDaoImpl();

    @Override
    protected Class getMyClass() {
        return this.getClass();
    }

    public String login(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//        获取两个参数 accout 和password 输出为html页面
        req.setCharacterEncoding("UTF-8");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        Student stu = null;
        Member member = null;
        try {
            stu = studentDao.login(account,password);
            if(stu != null){
                member = (Member) memberDao.queryByNumber(stu.getStudentNumber());
                HttpSession session = req.getSession();
                session.setAttribute("student",stu.getStudentNumber());
                session.setAttribute("position",member);
                res.sendRedirect("/studentSociety/society/mainIndex");
                //res.sendRedirect("/society/mainIndex");
            }else{
                req.getRequestDispatcher("/index.jsp?message= account or password is wrong").forward(req,res);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables,req,res);
        }
        return "direct";
    }
    public String queryStudent(HttpServletRequest req, HttpServletResponse res) throws ServerException, IOException, ServletException {
        String name = req.getParameter("name");
        String number = req.getParameter("number");
        List<Student> students = null;
        try {
            students = studentDao.queryStudent(name, number);
            req.setAttribute("students", students);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception", throwables);
            return "error";
        }
        req.getRequestDispatcher("/member/addPage").forward(req, res);
        return "member/addStudent";
    }
}